package org.example.aidemo.scheduler;

import org.example.aidemo.pojo.Location;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LocationManagerScheduler {
    private final Map<String, Location> locationCache = new ConcurrentHashMap<>();
    private final Map<String, LocalDateTime> lastUpdateTimes = new ConcurrentHashMap<>();

    // 设置位置信息过期时间（例如5分钟）
    private static final long EXPIRATION_TIME = 5 * 60 * 1000;

    public void updateLocation(String userId, Location location) {
        locationCache.put(userId, location);
        lastUpdateTimes.put(userId, LocalDateTime.now());
    }

    public Location getLocation(String userId) {
        LocalDateTime lastUpdate = lastUpdateTimes.get(userId);
        if (lastUpdate != null &&
                LocalDateTime.now().isBefore(lastUpdate.plusMinutes(5))) {
            return locationCache.get(userId);
        }
        return null; // 位置信息已过期
    }

    // 添加清理方法
    public void cleanupExpiredLocations() {
        LocalDateTime now = LocalDateTime.now();
        Iterator<Map.Entry<String, LocalDateTime>> timeIterator = lastUpdateTimes.entrySet().iterator();

        while (timeIterator.hasNext()) {
            Map.Entry<String, LocalDateTime> entry = timeIterator.next();
            if (now.isAfter(entry.getValue().plusMinutes(5))) {
                // 移除过期项
                timeIterator.remove();
                locationCache.remove(entry.getKey());
            }
        }
    }
    // 定时执行清理任务
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void scheduledCleanup() {
        cleanupExpiredLocations();
    }
}
